package com.mengdie.shuidi.ui.dialog;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.FileProvider;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.utils.EmptyUtils;
import com.blankj.utilcode.utils.LogUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.mengdie.shuidi.AppContext;
import com.mengdie.shuidi.R;
import com.mengdie.shuidi.common.ClientConfig;
import com.mengdie.shuidi.helper.UIHelper;
import com.mengdie.shuidi.model.UpdateEntity;
import com.mengdie.shuidi.widgets.UpdataAPPProgressBar;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 作者：HQY on 2019/3/15 15:32
 * 邮箱：hqy_xz@126.com
 */
public class AppUpdateDialogFragment extends DialogFragment implements DialogInterface.OnKeyListener {


    @Bind(R.id.tv_update_version)
    TextView mTvUpdateVersion;
    @Bind(R.id.tv_update_content)
    TextView mTvUpdateContent;
    @Bind(R.id.uapb_update_progress)
    UpdataAPPProgressBar mUapbUpdateProgress;
    @Bind(R.id.ll_update_progress)
    LinearLayout mLlUpdateProgress;
    @Bind(R.id.tv_update_submit)
    TextView mTvUpdateSubmit;
    @Bind(R.id.rl_update_close)
    RelativeLayout mRlUpdateClose;

    private UpdateEntity mUpdate;
    private String mApkName;

    public static AppUpdateDialogFragment newInstance(UpdateEntity update) {
        Bundle args = new Bundle();
        args.putSerializable(UIHelper.MODEL, update);
        AppUpdateDialogFragment fragment = new AppUpdateDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (EmptyUtils.isNotEmpty(getArguments())) {
            mUpdate = (UpdateEntity) getArguments().getSerializable(UIHelper.MODEL);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().setCanceledOnTouchOutside(false);
        View rootView = inflater.inflate(R.layout.dialog_updates, container, false);
        ButterKnife.bind(this, rootView);
        final Window window = getDialog().getWindow();
        window.setBackgroundDrawableResource(R.color.reveal_five);
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        wlp.height = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(wlp);
        getDialog().setCanceledOnTouchOutside(false);
        getDialog().setCancelable(false);
        getDialog().setOnKeyListener(this);
        initView();
        return rootView;
    }


    private void initView() {
        mTvUpdateContent.setText(mUpdate.getDesc());
        mTvUpdateVersion.setText(mUpdate.getShowVersion());
        if (mUpdate.getForceUpdate().equals("true")) {
            mRlUpdateClose.setVisibility(View.GONE);
        } else {
            mRlUpdateClose.setVisibility(View.VISIBLE);
        }
        mApkName = getActivity().getResources().getString(R.string.app_name) + mUpdate.getShowVersion() + ".apk";
    }

    /**
     * 下载apk
     *
     * @param path
     * @param apkPath
     * @param name
     */
    private void downApk(String path, String apkPath, String name) {
        LogUtils.e("下载开始：" + path);
        OkGo.get(path)
                .tag(this)
                .execute(new FileCallback(apkPath, name) {
                    @Override
                    public void onSuccess(File file, Call call, okhttp3.Response response) {
                        install(getActivity(), ClientConfig.DEFAULT_SAVE_FILE_PATH, mApkName);
                    }

                    @Override
                    public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                        super.downloadProgress(currentSize, totalSize, progress, networkSpeed);
                        int rate = Math.round(progress * 100);
                        LogUtils.e("下载进度：" + rate);
                        mUapbUpdateProgress.setProgress(rate);
                    }
                });



    }

    /**
     * 通过隐式意图调用系统安装程序安装APK
     */
    public static void install(Context context, String apkPath, String apkName) {
        File file = new File(apkPath, apkName);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri =
                    FileProvider.getUriForFile(context, AppContext.getInstance().getPackageName() + ".fileprovider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
        }
        context.startActivity(intent);


    }

    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return false;
    }


    @OnClick({R.id.tv_update_submit, R.id.rl_update_close})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_update_submit:
                mTvUpdateSubmit.setVisibility(View.GONE);
                mLlUpdateProgress.setVisibility(View.VISIBLE);
                downApk(mUpdate.getDownloadPath(), ClientConfig.DEFAULT_SAVE_FILE_PATH, mApkName);
                break;
            case R.id.rl_update_close:
                dismiss();
                break;
        }
    }
}
